import axios from 'axios';
import store from '../store';
import { Message } from 'element-ui'
import router from '../router';
axios.defaults.baseURL = 'wlmtsys';//上线部署时才修改
axios.defaults.baseURL = 'http://121.37.242.119:20000';//开发
// 创建axios实例
var instance = axios.create({
	timeout: 1000 * 16
});

// 设置请求头
instance.defaults.headers.post['Content-Type'] = 'application/json';
// instance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
instance.defaults.headers.get['Content-Type'] = 'application/json';
instance.defaults.headers.put['Content-Type'] = 'application/json';
instance.defaults.headers.delete['Content-Type'] = 'application/json';
instance.defaults.headers.patch['Content-Type'] = 'application/json';

// 请求拦截器
instance.interceptors.request.use((config)=>{
	// 注入token
	if(store.getters.token){
		config.headers['authorization'] = store.getters.token;
	}
	return config
},(error)=>{
	// 失败执行promise
	return Promise.reject(error)
})


// 响应拦截器
instance.interceptors.response.use((response)=>{
	return response
},async (error)=>{
	console.log(error);
	console.log(error.status);
	
	if(error.status === 401){
		Message({type:'error',message:'登录已过期，请重新登录'})
		// 需要调用action删除token和用户信息，然后跳转到/login
		await store.dispatch('user/loginOut')
		router.push('/login')
		// 提示登录过期之后不在提示
		return Promise.reject(error)
	}
	Message({type:'error',message:error.message})
	return Promise.reject(error)
})



export default instance;
